/**
 * 实现Storage，使得该对象为单例，基于localstorage进行封装，实现方法setItem，getItem
 * 使用instance变量存唯一实例，getInstance方法，闭包或静态方法实现
 */

// 闭包方式
function Base() {}
Base.prototype.getItem = function(key) {
  return localStorage.getItem(key);
}
Base.prototype.setItem = function(key, value) {
  return localStorage.setItem(key, value);
}
const Storage = (function() {
  let instance = null;
  return function() {
    if (!instance) {
      instance = new Base();
    }
    return instance;
  }
})();

// 使用
const s1 = Storage();
const s2 = Storage();
console.log('s1===s2', s1 === s2);

// 类的方式
class Storage1 {
  static getInstance() {
    if (!Storage1.instance) {
      Storage1.instance = new Storage1();
    }
    return Storage1.instance;
  }

  getItem(key) {
    return localStorage.getItem(key);
  }

  setItem(key, value) {
    return localStorage.setItem(key, value);
  }
}
const s3 = Storage1.getInstance();
const s4 = Storage1.getInstance();
console.log('s3===s4', s3 === s4);
s3.setItem('name', 'mzn');
console.log(s4.getItem('name'));